package com.bj58.groupbuy.action.service.impl;

import java.util.HashSet;
import java.util.List;

import com.bj58.groupbuy.action.db.DBConfig;
import com.bj58.groupbuy.action.db.UserPriviledgeDao;
import com.bj58.groupbuy.action.model.Menu;
import com.bj58.groupbuy.action.model.RolePriviledge;
import com.bj58.groupbuy.action.model.User;
import com.bj58.groupbuy.action.model.UserPriviledge;
import com.bj58.groupbuy.action.model.UserRole;
import com.bj58.groupbuy.action.service.MenuService;
import com.bj58.groupbuy.action.service.RolePriviledgeService;
import com.bj58.groupbuy.action.service.UserManagerService;
import com.bj58.groupbuy.action.service.UserPriviledgeService;
import com.bj58.groupbuy.action.service.UserRoleService;
import com.bj58.groupbuy.action.util.MyStore;
import com.bj58.groupbuy.service.impl.BaseService;
import com.bj58.groupbuy.service.locator.ServiceLocator;
import com.bj58.groupbuy.util.security.Encrypt;
import com.bj58.groupbuy.wf.page.Paginate;

public class UserManagerServiceImpl extends BaseService<User> implements UserManagerService {

	
	private UserRoleService userRoleService = ServiceLocator.get(UserRoleService.class);
	private	RolePriviledgeService rolePriviledgeService = ServiceLocator.get(RolePriviledgeService.class);
	private	UserPriviledgeService userPriService = ServiceLocator.get(UserPriviledgeService.class);
	private MenuService menuService = ServiceLocator.get(MenuService.class);
	
	private static UserPriviledgeDao comDao = new UserPriviledgeDao();
	@Override
	public User getUserByName(String userName) throws Exception {
		String sql="select * from user where username='"+userName+"'";
		List<User> userList =comDao.getAllColsByVo(sql, User.class, DBConfig.db_68_bi_sys.getIntType());
		if(null != userList && !userList.isEmpty() ){
			return userList.get(0);
		}
		return null;
	}

	@Override
	public User getUserById(int uid) throws Exception {
		String sql="select * from user where id='"+uid+"'";
		List<User> userList =comDao.getAllColsByVo(sql, User.class, DBConfig.db_68_bi_sys.getIntType());
		if(null != userList && !userList.isEmpty() ){
			return userList.get(0);
		}
		return null;
	}
	
	@Override
	public User checkUser(String userName, String pwd) throws Exception {
		String where = "username='"+userName+"' and password='"+Encrypt.MD532(pwd)+"' and state = 1";
		String sql="select * from user where "+where;
		List<User> userList =comDao.getAllColsByVo(sql, User.class, DBConfig.db_68_bi_sys.getIntType());
		if(null != userList &&  !userList.isEmpty() && userList.size() == 1){
			return userList.get(0);
		}
		return null;
	}

	@Override
	public Paginate<User> getUserByPage(int pageIndex, int pageSize,String where) throws Exception {
		return getGenericDao().findForPage(User.class, where, "*", pageIndex, pageSize, "createtime desc");
	}

	@Override
	public List<User> getAllUsers() throws Exception {
		String sql="select * from user where state = 1";
		List<User> userList =comDao.getAllColsByVo(sql, User.class, DBConfig.db_68_bi_sys.getIntType());
		if(null != userList &&  !userList.isEmpty()){
			return userList;
		}
		return null;
	}

	@Override
	public boolean saveUser(User user) throws Exception {
		int res=comDao.insertOneByVo(null, "user", User.class, user, DBConfig.db_68_bi_sys.getIntType());
		return res==0?false:true;
	}

	@Override
	public boolean updateUser(User user) throws Exception {
		int res = comDao.updateByVo("user", "id=" + user.getId(), User.class, user, DBConfig.db_68_bi_sys.getIntType());
		return res==0?false:true;
	}

	@Override
	public boolean saveUserRole(User user, String roleIds, String functions,String opers)
			throws Exception {
		return comDao.saveUser(user, roleIds, functions, opers, DBConfig.db_68_bi_sys.getIntType());
	}

	@Override
	public boolean updateUserRole(User user, String roleids, String functions,String opers)
			throws Exception {
		return comDao.updateUserRole(user, roleids, functions, opers, DBConfig.db_68_bi_sys.getIntType());
	}

	@Override
	public User getUserByMd5(String md5) throws Exception {
		String sql="select * from user where md5='"+md5+"'";
		List<User> userList =comDao.getAllColsByVo(sql, User.class, DBConfig.db_68_bi_sys.getIntType());
		if(null != userList && !userList.isEmpty() && userList.size() == 1){
			return userList.get(0);
		}
		return null;
	}

	@Override
	public String getFunctionsByUser(User user) throws Exception {
		List<UserRole> userRoles = userRoleService.getByUserid(user.getId());
		HashSet<Long> funcSet = new HashSet<Long>();
		String functions = "";
		String priviousfunc = user.getFunction();
		if (MyStore.admin.equals(priviousfunc))
			return priviousfunc;
		if (priviousfunc != null && priviousfunc.length() > 0) {
			String f[] = priviousfunc.split(",");
			for (String func : f) {
				if (func.length() == 0 || funcSet.contains(func)){
					continue;
				}
				funcSet.add(Long.parseLong(func));
				functions += "," + func;
			}
		}
		if (userRoles != null)
			for (UserRole ur : userRoles) {
				List<RolePriviledge> rolePrivs = rolePriviledgeService.getPriviledgeByRoleid(ur.getRoleid());
				if (rolePrivs != null)
					for (RolePriviledge pri : rolePrivs) {
						if (funcSet.contains(pri.getMenuid())){
							continue;
						}
						funcSet.add(pri.getMenuid());
						functions += "," + pri.getMenuid();
					}
			}
		List<UserPriviledge> userPris = userPriService.getByUserid(user.getId());
		if (userPris != null)
			for (UserPriviledge up : userPris) {
				if (funcSet.contains(up.getMenuid())){
					continue;
				}
				funcSet.add(up.getMenuid());
				functions += "," + up.getMenuid();
			}
		if (functions.length() > 0){
			return functions.substring(1);
		}else{
			return "";
		}
	}

	@Override
	public String getNewAndOldUserFunc(User user, List<Menu> menuList)
			throws Exception {
		HashSet<Long> funcSet = new HashSet<Long>();
		String functions = "";
		String priviousfunc = user.getFunction();
		if (MyStore.admin.equals(priviousfunc)) {
			for (Menu m : menuList)
				functions += "," + m.getId();
			return functions;
		}
		if (priviousfunc != null && priviousfunc.length() > 0) {
			String f[] = priviousfunc.split(",");
			for (String func : f) {
				if (func.length() == 0 || funcSet.contains(func))
					continue;
				funcSet.add(Long.parseLong(func));
				functions += "," + func;
			}
		}
		List<UserPriviledge> userPris = userPriService.getByUserid(user.getId());
		if (userPris != null)
			for (UserPriviledge up : userPris) {
				if (funcSet.contains(up.getMenuid()))
					continue;
				funcSet.add(up.getMenuid());
				functions += "," + up.getMenuid();
			}
		return functions;
	}

	@Override
	public boolean checkUserMenuFuns(User user, String url) throws Exception {
		if(MyStore.admin.equals(user.getFunction())){ //管理员
			return true;
		}
		
//		if(url.contains("_")){
//			url = url.substring(0,url.lastIndexOf("_"));
//		}
		
		//用户所有菜单权限
		String funs = getFunctionsByUser(user);
		HashSet<Integer> funSet = new HashSet<Integer>();
		for(String fun : funs.split(",")){
			funSet.add(Integer.parseInt(fun));
		}
		
		Menu menu  = menuService.findByURL(url);
		if(null != menu && funSet.contains(menu.getId())){
			return true;
		}else{
			return false;
		}
	}
	
	
}
